import * as cc from 'cc';
import { Player } from '../Player';
import { InputCommand } from './InputComand';
import { KeyInput } from './KeyInput';

const { ccclass } = cc._decorator;

@ccclass('PlayerInputHandler')
export class PlayerInputHandler extends cc.Component {
    player: Player;
    inputCommand: InputCommand;
    keyInput: KeyInput;

    protected onLoad(): void {
        this.player = this.getComponent(Player);
        this.keyInput = this.addComponent(KeyInput);
        this.inputCommand = new InputCommand();
        this.handleJump();
        this.handleDash();
        this.handleAttack();
    }

    update(deltaTime: number) {
        this.inputCommand.executeCommand();
        this.handleMove();
    }

    handleJump() {
        this.inputCommand.onTrigger(
            'jump',
            () => {
                return (
                    this.keyInput.getKeyDown(cc.KeyCode.KEY_K) ||
                    this.keyInput.getKeyDown(cc.KeyCode.SPACE)
                );
            },
            () => {
                this.player.jump();
            },
        );
    }

    handleDash() {
        this.inputCommand.onTrigger(
            'dash',
            () => {
                return (
                    this.keyInput.getKeyDown(cc.KeyCode.SHIFT_LEFT) ||
                    this.keyInput.getKeyDown(cc.KeyCode.KEY_L)
                );
            },
            () => {
                this.player.dash();
            },
        );
    }

    handleAttack() {
        this.inputCommand.onTrigger(
            'attack',
            () => {
                return (
                    this.keyInput.getKeyDown(cc.KeyCode.KEY_J) ||
                    this.keyInput.getKeyDown(cc.KeyCode.KEY_Z)
                );
            },
            () => {
                this.player.attack();
            },
        );
    }

    handleMove() {
        // 移动输入检测
        let moveDir = 0;
        if (
            this.keyInput.getKey(cc.KeyCode.ARROW_LEFT) ||
            this.keyInput.getKey(cc.KeyCode.KEY_A)
        ) {
            moveDir = -1;
        }
        if (
            this.keyInput.getKey(cc.KeyCode.ARROW_RIGHT) ||
            this.keyInput.getKey(cc.KeyCode.KEY_D)
        ) {
            moveDir = 1;
        }
        this.player.moveTo(moveDir);
    }
}
